package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Query;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.entity.TemplateComponent;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.service.TemplateServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.exception.enums.ApprovalRespCodeDesc;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 获得审批模板详情 用户自定义
 *
 * @author Administrator
 */
@WebServlet("/getTemplateDetail")
public class GetTemplateDetail extends AbstractServlet {
    private static final long serialVersionUID = -6524473373623928868L;

    private static final Logger logger = LoggerFactory.getLogger(GetTemplateDetail.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * {templateId:4,version:>0}
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            User user = getReqUser(req);
            Template template = getTemplate(req);
            check(template);

            template.setCompanyId(user.getCompanyId());
            Integer userGeneration = getUserGeneration(req);

//            if (!ApprovalUtils.isTestCompany(user.getCompanyId())) {
//                ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
//                template = readTemplateServicePrx.getTemplateDetail(template);
//            } else {
//                Query query = new Query(user);
//                query.setTemplateId(template.getTemplateId());
//                query.setVersionInfo(getVersionInfo(req));
//                TemplateServicePrx templateServicePrx = ServantUtils.getObject(TemplateServicePrx.class);
//                template = templateServicePrx.getTemplateDetail(query);
//            }
            Query query = new Query(user);
            query.setTemplateId(template.getTemplateId());
            query.setVersionInfo(getVersionInfo(req));
            TemplateServicePrx templateServicePrx = ServantUtils.getObject(TemplateServicePrx.class);
            template = templateServicePrx.getTemplateDetail(query);

            if (ApprovalUtils.checkNotAuthGeneration(userGeneration, template.getTemplateGeneration())) {
                throw new RpcServerLogicalException(1, "请更新大管加版本");
            }

            List<TemplateComponent> templateComponents = getTemplateComponentList(template);

            returnResp(resp, template, templateComponents);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void returnResp(HttpServletResponse resp, Template template, List<TemplateComponent> templateComponents) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "获得成功");
        jsonObject.put("template", template);
        jsonObject.put("component", templateComponents);

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    private List<TemplateComponent> getTemplateComponentList(Template template) {
        String component = template.getTemplateComponent();
        List<TemplateComponent> templateComponents;
        try {
            templateComponents = JSONArray.parseArray(component, TemplateComponent.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(ApprovalRespCodeDesc.DATABASE_DATAERROR);
        }
        return templateComponents;
    }

    private Template getTemplate(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数 {}", reqBody);

        Template template;
        try {
            template = JSONObject.parseObject(reqBody, Template.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批查看失败，请稍候再试");
        }
        return template;
    }

    protected void check(Template template) {
        if (template.getTemplateId() == 0 || template.getVersion() == 0) {
            throw new RpcServerLogicalException(1, "模板参数不正确");
        }
    }

}
